package sit.engreal.leetcode.problems900;

import org.junit.jupiter.api.Assertions;

/**
 * <a href="https://leetcode.cn/problems/peak-index-in-a-mountain-array/">852. 山脉数组的峰顶索引</a>
 */
public class LeetCode852 {
    public int peakIndexInMountainArray(int[] arr) {
        int step = arr.length / 2;
        int position = 0;
        while (step != 0) {
            final int left = position - step;
            final int right = position + step;

            final int leftValue = (left < 0 || left >= arr.length) ? Integer.MIN_VALUE : arr[left];
            final int rightValue = (right < 0 || right >= arr.length) ? Integer.MIN_VALUE : arr[right];
            if (leftValue > arr[position]) {
                position = left;
            } else if (rightValue > arr[position]) {
                position = right;
            } else {
                step /= 2;
            }

        }
        return position;
    }

    public static void main(String[] args) {
        final LeetCode852 demo = new LeetCode852();
        Assertions.assertEquals(2,
                demo.peakIndexInMountainArray(new int[]{24, 69, 100, 99, 79, 78, 67, 36, 26, 19}));
        Assertions.assertEquals(1, demo.peakIndexInMountainArray(new int[]{0, 1, 0}));
        Assertions.assertEquals(1, demo.peakIndexInMountainArray(new int[]{0, 2, 1, 0}));
        Assertions.assertEquals(1, demo.peakIndexInMountainArray(new int[]{0, 10, 5, 2}));
    }
}
